package apis

import (
    "crypto/md5"
    "encoding/hex"
    "errors"
    "fmt"
    log "github.com/go-admin-team/go-admin-core/logger"
    "github.com/go-admin-team/go-admin-core/sdk/pkg/utils"
    "github.com/xiam/to"
    "github.com/xuri/excelize/v2"
    "io"
    "net/http"
    "strings"

    "github.com/gin-gonic/gin"
    "github.com/go-admin-team/go-admin-core/sdk/api"
    "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
    _ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"

    "go-admin/app/hunter/models"
    "go-admin/app/hunter/service"
    "go-admin/app/hunter/service/dto"
    "go-admin/common/actions"
)

type HtTalent struct {
    api.Api
}

// GetPage 获取HtTalent列表
// @Summary 获取HtTalent列表
// @Description 获取HtTalent列表
// @Tags HtTalent
// @Param name query string false "姓名"
// @Param phone query string false "手机号"
// @Param sex query string false "性别"
// @Param level query string false "评级"
// @Param note query string false "备注信息"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]models.HtTalent}} "{"code": 200, "data": [...]}"
// @Router /api/v1/ht-talent [get]
// @Security Bearer
func (e HtTalent) GetPage(c *gin.Context) {
    req := dto.HtTalentGetPageReq{}
    s := service.HtTalent{}
    err := e.MakeContext(c).
        MakeOrm().
        Bind(&req).
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }

    p := actions.GetPermissionFromContext(c)
    list := make([]models.HtTalent, 0)
    var count int64

    err = s.GetPage(&req, p, &list, &count)
    if err != nil {
        e.Error(500, err, fmt.Sprintf("获取HtTalent失败，\r\n失败信息 %s", err.Error()))
        return
    }

    e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// GetPageWithoutProject GetPage 获取HtTalent列表
// @Summary 获取HtTalent列表
// @Description 获取HtTalent列表
// @Tags HtTalent
// @Param name query string false "姓名"
// @Param phone query string false "手机号"
// @Param sex query string false "性别"
// @Param level query string false "评级"
// @Param note query string false "备注信息"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]models.HtTalent}} "{"code": 200, "data": [...]}"
// @Router /api/v1/ht-talent1 [get]
// @Security Bearer
func (e HtTalent) GetPageWithoutProject(c *gin.Context) {
    req := dto.HtTalentGetPageReq{}
    s := service.HtTalent{}
    err := e.MakeContext(c).
        MakeOrm().
        Bind(&req).
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }

    p := actions.GetPermissionFromContext(c)
    list := make([]models.HtTalent, 0)
    var count int64

    err = s.GetPageWithoutProjectId(&req, p, &list, &count)
    if err != nil {
        e.Error(500, err, fmt.Sprintf("获取HtTalent失败，\r\n失败信息 %s", err.Error()))
        return
    }

    e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Get 获取HtTalent
// @Summary 获取HtTalent
// @Description 获取HtTalent
// @Tags HtTalent
// @Param id path int false "id"
// @Success 200 {object} response.Response{data=models.HtTalent} "{"code": 200, "data": [...]}"
// @Router /api/v1/ht-talent/{id} [get]
// @Security Bearer
func (e HtTalent) Get(c *gin.Context) {
    req := dto.HtTalentGetReq{}
    s := service.HtTalent{}
    err := e.MakeContext(c).
        MakeOrm().
        Bind(&req).
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }
    var object models.HtTalent

    p := actions.GetPermissionFromContext(c)
    err = s.Get(&req, p, &object)
    if err != nil {
        e.Error(500, err, fmt.Sprintf("获取HtTalent失败，\r\n失败信息 %s", err.Error()))
        return
    }

    e.OK(object, "查询成功")
}

// Insert 创建HtTalent
// @Summary 创建HtTalent
// @Description 创建HtTalent
// @Tags HtTalent
// @Accept application/json
// @Product application/json
// @Param data body dto.HtTalentInsertReq true "data"
// @Success 200 {object} response.Response	"{"code": 200, "message": "添加成功"}"
// @Router /api/v1/ht-talent [post]
// @Security Bearer
func (e HtTalent) Insert(c *gin.Context) {
    req := dto.HtTalentInsertReq{}
    s := service.HtTalent{}
    err := e.MakeContext(c).
        MakeOrm().
        Bind(&req).
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }
    // 设置创建人
    req.SetCreateBy(user.GetUserId(c))

    err = s.Insert(&req)
    if err != nil {
        e.Error(500, err, fmt.Sprintf("创建HtTalent失败，\r\n失败信息 %s", err.Error()))
        return
    }

    e.OK(req.GetId(), "创建成功")
}

// Update 修改HtTalent
// @Summary 修改HtTalent
// @Description 修改HtTalent
// @Tags HtTalent
// @Accept application/json
// @Product application/json
// @Param id path int true "id"
// @Param data body dto.HtTalentUpdateReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "修改成功"}"
// @Router /api/v1/ht-talent/{id} [put]
// @Security Bearer
func (e HtTalent) Update(c *gin.Context) {
    req := dto.HtTalentUpdateReq{}
    s := service.HtTalent{}
    err := e.MakeContext(c).
        MakeOrm().
        Bind(&req).
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }
    req.SetUpdateBy(user.GetUserId(c))
    p := actions.GetPermissionFromContext(c)

    err = s.Update(&req, p)
    if err != nil {
        e.Error(500, err, fmt.Sprintf("修改HtTalent失败，\r\n失败信息 %s", err.Error()))
        return
    }
    e.OK(req.GetId(), "修改成功")
}

// Delete 删除HtTalent
// @Summary 删除HtTalent
// @Description 删除HtTalent
// @Tags HtTalent
// @Param data body dto.HtTalentDeleteReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "删除成功"}"
// @Router /api/v1/ht-talent [delete]
// @Security Bearer
func (e HtTalent) Delete(c *gin.Context) {
    s := service.HtTalent{}
    req := dto.HtTalentDeleteReq{}
    err := e.MakeContext(c).
        MakeOrm().
        Bind(&req).
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }

    // req.SetUpdateBy(user.GetUserId(c))
    p := actions.GetPermissionFromContext(c)

    err = s.Remove(&req, p)
    if err != nil {
        e.Error(500, err, fmt.Sprintf("删除HtTalent失败，\r\n失败信息 %s", err.Error()))
        return
    }
    e.OK(req.GetId(), "删除成功")
}

// Import  导入HtTalent
// @Summary 导入HtTalent
// @Description 导入HtTalent
// @Tags HtTalent
// @Accept multipart/form-data
// @Param file formData file true "file"
// @Success 200 {object} response.Response	"{"code": 200, "message": "导入成功"}"
// @Router /api/v1/ht-talent/importData [post]
// @Security Bearer
func (e HtTalent) Import(c *gin.Context) {
    s := service.HtTalent{}
    err := e.MakeContext(c).
        MakeOrm().
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }

    // req.SetUpdateBy(user.GetUserId(c))
    p := actions.GetPermissionFromContext(c)
    talents := make([]models.HtTalent, 0)
    files, err := c.FormFile("file")

    file, err := files.Open()
    if err != nil {
        e.Error(http.StatusInternalServerError, err, fmt.Sprintf("文件打开失败: %s", err.Error()))
        return
    }
    defer file.Close()

    // Parse the Excel file
    f, err := excelize.OpenReader(file)
    if err != nil {
        e.Error(http.StatusInternalServerError, err, fmt.Sprintf("解析Excel文件失败: %s", err.Error()))
        return
    }
    for i := 0; i < f.SheetCount; i++ {
        rows, err := f.GetRows(f.GetSheetName(i))
        if err != nil {
            e.Error(http.StatusInternalServerError, err, fmt.Sprintf("读取Excel文件行失败: %s", err.Error()))
            return
        }
    out:
        for _, row := range rows {
            var talent models.HtTalent
            add := false
            for i, colCell := range row {
                switch i {
                case 0:
                    if strings.HasPrefix(colCell, "#") {
                        continue out
                    }
                    talent.Name = colCell
                    add = true
                case 1:
                    talent.Phone = colCell
                    add = true
                case 2:
                    talent.Note = colCell
                    add = true
                }
            }
            if add {
                talents = append(talents, talent)
            }
        }
    }

    count := len(talents)
    if count >= 0 {
        err = s.BatchInsert(talents, p)
        if err != nil {
            e.Error(500, err, fmt.Sprintf("导入人才插入失败，\r\n失败信息 %s", err.Error()))
            return
        }
        projectId := to.Int(c.Request.Form.Get("projectId"))
        if projectId > 0 {
            projectTalents := make([]models.HtProjectTalent, 0)
            for _, t := range talents {
                projectTalents = append(projectTalents, models.HtProjectTalent{ProjectId: projectId, TalentId: t.Id})
            }
            err = s.BatchBindInsert(projectTalents, p)
            if err != nil {
                e.Error(500, err, fmt.Sprintf("导入人才绑定失败，\r\n失败信息 %s", err.Error()))
                return
            }
        }
    }
    e.OK(count, "导入成功")
}

// UploadResume  导入HtTalent简历
// @Summary 导入HtTalent简历
// @Description 导入HtTalent
// @Tags HtTalent
// @Accept multipart/form-data
// @Param file formData file true "file"
// @Success 200 {object} response.Response	"{"code": 200, "message": "上传简历成功"}"
// @Router /api/v1/ht-talent/uploadResume [post]
// @Security Bearer
func (e HtTalent) UploadResume(c *gin.Context) {
    s := service.HtTalent{}
    talentId, ok := c.GetPostForm("id")
    talentId32 := to.Int(talentId)
    if !ok || talentId32 <= 0 {
        e.Error(200, errors.New("没有候选人id"), "没有携带候选人id")
        return
    }
    var talent models.HtTalent
    talent.Id = talentId32
    err := e.MakeContext(c).
        MakeOrm().
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }
    err = e.Orm.First(&talent).Error
    if err != nil {
        e.Error(200, errors.New("候选人id错误"), "候选人id错误")
        return
    }
    // req.SetUpdateBy(user.GetUserId(c))
    p := actions.GetPermissionFromContext(c)
    _ = p
    form, err := c.MultipartForm()
    files := form.File["upload[]"]
    path := "static/resume/"
    err = utils.IsNotExistMkDir(path)
    if err != nil {
        e.Error(500, errors.New(""), "初始化简历文件路径失败")
    }
    list := make([]models.HtResume, 0)
    for _, file := range files {
        f, _ := file.Open()
        // 创建一个新的MD5哈希对象
        hasher := md5.New()

        // 将文件内容复制到哈希对象
        if _, err := io.Copy(hasher, f); err != nil {
            e.Error(500, errors.New(""), "md5计算错误")
            return
        }

        // 计算哈希值
        hashInBytes := hasher.Sum(nil)

        // 将哈希值转换成字符串
        hashInString := hex.EncodeToString(hashInBytes)
        fileName := path + hashInString + utils.GetExt(file.Filename)
        if utils.CheckExist(fileName) {
            _ = c.SaveUploadedFile(file, fileName)
        }
        var resume models.HtResume
        resume.TalentId = talentId32
        resume.FileUri = hashInString + utils.GetExt(file.Filename)
        err = e.Orm.Create(&resume).Error
        if err != nil {
            log.Error("link talent resume error")
        }
        list = append(list, resume)
    }

    // bind file 2 talent
    e.OK(list, "上传简历成功")
}

// DeleteResume 删除HtTalent简历
// @Summary 删除HtTalent简历
// @Description 删除HtTalent简历
// @Tags HtTalentResume
// @Param data body dto.HtTalentDeleteReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "删除成功"}"
// @Router /api/v1/ht-talent/resume [delete]
// @Security Bearer
func (e HtTalent) DeleteResume(c *gin.Context) {
    s := service.HtTalent{}
    req := dto.HtTalentResumeDeleteReq{}
    err := e.MakeContext(c).
        MakeOrm().
        Bind(&req).
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }

    // req.SetUpdateBy(user.GetUserId(c))
    // bind file 2 talent
    p := actions.GetPermissionFromContext(c)

    err = s.RemoveResume(&req, p)
    if err != nil {
        e.Error(500, err, fmt.Sprintf("删除HtTalent失败，\r\n失败信息 %s", err.Error()))
        return
    }
    e.OK(req.FileUri, "删除成功")
}

// Count 查询候选人总数
// @Summary 查询候选人总数
// @Description 查询候选人总数
// @Tags HtTalent
// @Success 200 {object} "{"code": 200, "message": "查询成功", "data":count}"
// @Router /api/v1/ht-talent/count [get]
// @Security Bearer
func (e HtTalent) Count(c *gin.Context) {
    req := dto.HtTalentGetPageReq{}
    s := service.HtTalent{}
    err := e.MakeContext(c).
        MakeOrm().
        Bind(&req).
        MakeService(&s.Service).
        Errors
    if err != nil {
        e.Logger.Error(err)
        e.Error(500, err, err.Error())
        return
    }

    var count int64
    e.Orm.Table(models.HtTalent{}.TableName()).Where("deleted_at is null").Count(&count)

    e.OK(count, "查询成功")
}
